package com.watson.threadlocal;

/**
 * @Description: TODO
 * @Author watson
 * @Date 2022/8/3 20:18
 * @Version 1.0
 */
public class ThrealLocalDemo  {

    private static String testStr = null;

    public static void main(String[] args) {

        //用于测试不用线程有自己的线程副本，操作不安全的线程变量不会相互影响
        Runnable r1 = () -> {
            ThreadLocal threadLocal = new ThreadLocal<String>();
            ThreadLocal s = new ThreadLocal();
            testStr = "我是线程1设置的值";
            threadLocal.set(testStr);
            System.out.println(threadLocal.get());
        };

        //用于测试子线程的本地副本变量的传递，主要通过InheritableThreadLocal来传递，在创建InheritableThreadLocal的
        //时候，会ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; Thread在初始化的时候会把父线程的inheritableThreadLocals复制给子线程作为初始值
        Runnable r2 = () -> {
            ThreadLocal threadLocal = new InheritableThreadLocal();
            testStr = "我是线程2设置的值";
            threadLocal.set(testStr);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("我是线程3  我打印了:" + threadLocal.get());
                }
            }, "线程3").start();

        };

        Runnable r4 = () -> {
            ThreadLocal threadLocal = new ThreadLocal();
            testStr = "我是线程4设置的值";
            threadLocal.set(testStr);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("我是线程5  我打印了:" + threadLocal.get());
                }
            }, "线程3").start();

        };

        new Thread(r1, "线程1").start();
        new Thread(r2, "线程1").start();
        new Thread(r4, "线程4").start();
    }


}

